/**
 * create by hp
 * date 2020/3/7 12:30
 * @type {string[]}
 */

import * as fs from 'fs'
import {rootPath} from "./rootPath"
import {evnArray} from "./env"

/**
 * 读取配置
 * @param evn
 */
const readConf = (evn: string): string => {
  if (!evnArray.includes(evn)) throw new Error(`${evn}环境不存在，请检查`)
  const confPath = `${rootPath}.env.${evn}`

  if (fs.existsSync(confPath)) {
    const res: Buffer = fs.readFileSync(confPath)
    return res.toString()
  }
  return ''
}

type conf = { name: string, value: string }

/**
 * 解析配置
 * @param confStr
 */
const analyseConf = (confStr: string): Array<conf> => {
  if (confStr !== null) confStr = confStr.replace(' ', '')
  if (confStr === null || confStr === '') return []

  const confTemp = confStr.split(/[\r\n]/)
  return confTemp.filter(item => {
    const tempStr: string = item.replace(' ', '')
    if (tempStr !== '') return true
  }).map(item => {
    let array = item.replace(/\s+/g, '').split('=')
    if (array.length !== 2) throw new Error('配置文件的格式存在问题，请检查')
    return {
      name: array[0],
      value: array[1]
    }
  })
}

/**
 * 获取配置
 * @param option
 */
const getConf = (option: { confNames?: Array<string>, evn: string }): Array<conf> => {
  const confStr = readConf(option.evn)
  const confArray = analyseConf(confStr)
  if (option.confNames && option.confNames.length > 0) {
    const resArray = confArray.filter(item => {
      for (let confName of option.confNames) {
        if (confName === item.name) return true
      }
    })
    if (resArray.length === 0) throw new Error('查询不到相关的配置')
    return resArray
  }
  return confArray
}

export {
  getConf
}
